<script setup>
import { ref, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { getSalaryStandardList, getSalaryStandardDetail } from '@/api/salary'
import { getOrganizationList, getPositionOptions, getPositionList } from '@/api/system'

const searchForm = ref({
  keyword: '',
  organization: undefined,
  position: undefined,
  status: undefined,
})

const columns = [
  { title: '标准编号', dataIndex: 'code', key: 'code', width: 120 },
  { title: '标准名称', dataIndex: 'name', key: 'name', width: 200 },
  { title: '适用机构', dataIndex: 'org', key: 'org', width: 150 },
  { title: '适用职位', dataIndex: 'position', key: 'position', width: 120 },
  { title: '生效日期', dataIndex: 'effectiveDate', key: 'effectiveDate', width: 120 },
  { title: '状态', dataIndex: 'status', key: 'status', width: 100 },
  { title: '操作', key: 'action', width: 150 },
]

const dataSource = ref([])
const loading = ref(false)

// 分页相关
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showTotal: (total) => `共 ${total} 条`,
})

// 详情弹窗相关
const detailVisible = ref(false)
const detailLoading = ref(false)
const detailData = ref({})

// 机构选项
const organizationOptions = ref([])
// 职位选项
const positionOptions = ref([])

// 获取机构选项
const fetchOrganizationOptions = async () => {
  try {
    // 直接使用机构列表接口，因为它包含了 id 信息
    const listResponse = await getOrganizationList()
    if (listResponse && listResponse.list) {
      // 扁平化机构列表
      const flattenOrganizations = (orgs) => {
        const result = []
        orgs.forEach((org) => {
          result.push({
            id: typeof org.id === 'string' ? parseInt(org.id, 10) : org.id,
            code: org.code,
            name: org.name,
          })
          if (org.children && org.children.length > 0) {
            result.push(...flattenOrganizations(org.children))
          }
        })
        return result
      }

      const flattenedList = flattenOrganizations(listResponse.list)
      // 直接从列表构建选项，并保存 id 信息
      organizationOptions.value = flattenedList.map((org) => ({
        value: org.code,
        label: org.name,
        id: org.id, // 保存 id，这样就不需要映射了
      }))
    } else {
      organizationOptions.value = []
    }
  } catch (error) {
    console.error('获取机构选项失败:', error)
    organizationOptions.value = []
  }
}

// 获取职位选项（根据机构过滤）
const fetchPositionOptions = async (organizationCode) => {
  try {
    // 如果提供了机构 code，直接从选项中找到对应的 id
    let organizationId = undefined
    if (organizationCode) {
      const orgOption = organizationOptions.value.find((opt) => opt.value === organizationCode)
      if (orgOption && orgOption.id) {
        organizationId = orgOption.id
      }
      console.log('职位选项 - 机构查找:', {
        organizationCode,
        organizationId,
        orgOption,
      })
    }

    console.log('调用职位选项接口:', {
      organizationCode,
      organizationId,
    })

    // 优先使用 list 接口，因为它返回的数据更完整
    const listResponse = await getPositionList(undefined, organizationId)
    console.log('职位列表接口响应:', listResponse)

    if (listResponse && listResponse.list) {
      // 从 list 接口构建职位选项
      positionOptions.value = listResponse.list.map((position) => ({
        value: position.code,
        label: position.name,
      }))
    } else {
      // 如果 list 接口失败，回退到 options 接口
      const optionsResponse = await getPositionOptions(organizationId)
      console.log('职位选项接口响应:', optionsResponse)

      if (optionsResponse && optionsResponse.list) {
        positionOptions.value = optionsResponse.list.map((item) => ({
          value: item.value,
          label: item.label,
        }))
      } else {
        positionOptions.value = []
      }
    }
  } catch (error) {
    console.error('获取职位选项失败:', error)
    positionOptions.value = []
  }
}

// 处理机构选择变化
const handleOrganizationChange = (value) => {
  // 如果先选了职位，再选机构，清空职位并刷新职位列表
  if (searchForm.value.position) {
    searchForm.value.position = undefined
  }
  // 根据选择的机构刷新职位列表
  fetchPositionOptions(value)
}

// 获取薪酬标准列表
const fetchStandardList = async (page = 1, pageSize = 10) => {
  loading.value = true
  try {
    const params = {
      page,
      pageSize,
    }

    // 处理 keyword 参数
    if (searchForm.value.keyword && searchForm.value.keyword.trim()) {
      params.keyword = searchForm.value.keyword.trim()
    }

    // 处理 organization 参数
    if (searchForm.value.organization) {
      params.organization = searchForm.value.organization
    }

    // 处理 position 参数
    if (searchForm.value.position) {
      params.position = searchForm.value.position
    }

    // 处理 status 参数
    if (searchForm.value.status) {
      params.status = searchForm.value.status
    }

    // 移除 undefined 的字段
    Object.keys(params).forEach((key) => {
      if (params[key] === undefined) {
        delete params[key]
      }
    })

    const response = await getSalaryStandardList(params)

    // 处理返回的分页数据
    if (response && response.list) {
      dataSource.value = response.list.map((item) => ({
        ...item,
        code: item.standardCode, // 映射 standardCode 到 code
        name: item.standardName, // 映射 standardName 到 name
        org: item.organization, // 映射 organization 到 org
        key: item.id,
      }))
      // 更新分页信息
      pagination.value.total = response.total || 0
      pagination.value.current = response.page || page
      pagination.value.pageSize = response.pageSize || pageSize
    } else {
      dataSource.value = []
      pagination.value.total = 0
    }
  } catch (error) {
    console.error('获取薪酬标准列表失败:', error)
    dataSource.value = []
    pagination.value.total = 0
  } finally {
    loading.value = false
  }
}

// 处理分页变化
const handleTableChange = (pag) => {
  pagination.value.current = pag.current
  pagination.value.pageSize = pag.pageSize
  fetchStandardList(pag.current, pag.pageSize)
}

const handleSearch = () => {
  pagination.value.current = 1
  fetchStandardList(1, pagination.value.pageSize)
}

const handleReset = () => {
  searchForm.value = {
    keyword: '',
    organization: undefined,
    position: undefined,
    status: undefined,
  }
  pagination.value.current = 1
  fetchStandardList(1, pagination.value.pageSize)
}

const handleExport = () => {
  // TODO: 调用导出接口
  message.info('导出功能待实现')
}

// 获取薪酬标准详情
const fetchStandardDetail = async (id) => {
  if (!id) {
    message.error('缺少标准ID')
    return
  }

  detailLoading.value = true
  try {
    const response = await getSalaryStandardDetail(id)

    // 处理返回的数据
    if (response) {
      detailData.value = {
        ...response,
        // 将 items 数组转换为便于显示的格式
        items: response.items || [],
      }
    } else {
      detailData.value = {}
      message.warning('未获取到详情数据')
    }
  } catch (error) {
    console.error('获取薪酬标准详情失败:', error)
    // handleApiError 已经处理了错误提示
    detailData.value = {}
  } finally {
    detailLoading.value = false
  }
}

// 打开详情弹窗
const handleViewDetail = async (record) => {
  detailVisible.value = true
  await fetchStandardDetail(record.id)
}

// 关闭详情弹窗
const handleCloseDetail = () => {
  detailVisible.value = false
  detailData.value = {}
}

onMounted(async () => {
  // 确保机构选项和映射表都已加载完成
  await fetchOrganizationOptions()
  // 初始化时如果有选择的机构，根据机构加载职位
  if (searchForm.value.organization) {
    await fetchPositionOptions(searchForm.value.organization)
  } else {
    await fetchPositionOptions()
  }
  fetchStandardList(1, pagination.value.pageSize)
})
</script>

<template>
  <div class="page-container">
    <div class="page-header">
      <h1 class="page-title">薪酬标准查询</h1>
      <p class="page-desc">查询和统计分析薪酬标准数据，支持按机构、职位查询对应薪酬标准</p>
    </div>

    <div class="page-content">
      <div class="search-card">
        <div class="search-form">
          <a-row :gutter="16">
            <a-col :span="6">
              <a-input v-model:value="searchForm.keyword" placeholder="标准编号/名称" allow-clear />
            </a-col>
            <a-col :span="6">
              <a-select
                v-model:value="searchForm.organization"
                placeholder="适用机构"
                allow-clear
                style="width: 100%"
                @change="handleOrganizationChange"
              >
                <a-select-option
                  v-for="option in organizationOptions"
                  :key="option.value"
                  :value="option.value"
                >
                  {{ option.label }}
                </a-select-option>
              </a-select>
            </a-col>
            <a-col :span="6">
              <a-select
                v-model:value="searchForm.position"
                placeholder="适用职位"
                allow-clear
                style="width: 100%"
                :disabled="!searchForm.organization"
              >
                <a-select-option
                  v-for="option in positionOptions"
                  :key="option.value"
                  :value="option.value"
                >
                  {{ option.label }}
                </a-select-option>
              </a-select>
            </a-col>
            <a-col :span="6">
              <a-select
                v-model:value="searchForm.status"
                placeholder="状态"
                allow-clear
                style="width: 100%"
              >
                <a-select-option value="已生效">已生效</a-select-option>
                <a-select-option value="待复核">待复核</a-select-option>
                <a-select-option value="已停用">已停用</a-select-option>
              </a-select>
            </a-col>
          </a-row>
          <div class="search-actions">
            <a-space>
              <a-button type="primary" @click="handleSearch">查询</a-button>
              <a-button @click="handleReset">重置</a-button>
              <a-button @click="handleExport">导出</a-button>
            </a-space>
          </div>
        </div>
      </div>

      <div class="table-wrapper">
        <a-table
          :columns="columns"
          :data-source="dataSource"
          :loading="loading"
          :pagination="pagination"
          @change="handleTableChange"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'status'">
              <a-tag
                :color="
                  record.status === '已生效'
                    ? 'green'
                    : record.status === '待复核'
                      ? 'orange'
                      : 'red'
                "
              >
                {{ record.status }}
              </a-tag>
            </template>
            <template v-if="column.key === 'action'">
              <a-button type="link" size="small" @click="handleViewDetail(record)"
                >查看详情</a-button
              >
            </template>
          </template>
        </a-table>
      </div>
    </div>

    <!-- 详情弹窗 -->
    <a-modal
      v-model:open="detailVisible"
      title="薪酬标准详情"
      width="800px"
      :footer="null"
      @cancel="handleCloseDetail"
    >
      <a-spin :spinning="detailLoading">
        <div v-if="!detailLoading && Object.keys(detailData).length > 0" class="detail-content">
          <a-card title="基本信息" class="detail-section" :bordered="false">
            <a-descriptions :column="2" bordered>
              <a-descriptions-item label="标准编号">{{ detailData.code }}</a-descriptions-item>
              <a-descriptions-item label="标准名称">{{ detailData.name }}</a-descriptions-item>
              <a-descriptions-item label="适用机构">{{ detailData.org }}</a-descriptions-item>
              <a-descriptions-item label="适用职位">{{ detailData.position }}</a-descriptions-item>
              <a-descriptions-item label="生效日期">{{
                detailData.effectiveDate
              }}</a-descriptions-item>
              <a-descriptions-item label="失效日期">{{
                detailData.expireDate || '长期有效'
              }}</a-descriptions-item>
              <a-descriptions-item label="状态">
                <a-tag
                  :color="
                    detailData.status === '已生效'
                      ? 'green'
                      : detailData.status === '待复核'
                        ? 'orange'
                        : 'red'
                  "
                >
                  {{ detailData.status }}
                </a-tag>
              </a-descriptions-item>
            </a-descriptions>
          </a-card>

          <a-card title="薪酬明细" class="detail-section" :bordered="false">
            <div v-if="detailData.items && detailData.items.length > 0" class="items-container">
              <!-- 应发项目 -->
              <div
                v-if="detailData.items.filter((item) => item.type === '应发项目').length > 0"
                class="items-group"
              >
                <div class="items-group-title">应发项目</div>
                <a-descriptions :column="2" bordered>
                  <a-descriptions-item
                    v-for="item in detailData.items.filter((i) => i.type === '应发项目')"
                    :key="item.itemName"
                    :label="item.itemName"
                  >
                    ¥{{ item.amount?.toLocaleString() || '0' }}
                  </a-descriptions-item>
                </a-descriptions>
              </div>

              <!-- 扣款项目 -->
              <div
                v-if="detailData.items.filter((item) => item.type === '扣款项目').length > 0"
                class="items-group"
              >
                <div class="items-group-title">扣款项目</div>
                <a-descriptions :column="2" bordered>
                  <a-descriptions-item
                    v-for="item in detailData.items.filter((i) => i.type === '扣款项目')"
                    :key="item.itemName"
                    :label="item.itemName"
                  >
                    ¥{{ item.amount?.toLocaleString() || '0' }}
                  </a-descriptions-item>
                </a-descriptions>
              </div>
            </div>
            <a-empty v-else description="暂无薪酬明细" />
          </a-card>

          <a-card title="其他信息" class="detail-section" :bordered="false">
            <a-descriptions :column="2" bordered>
              <a-descriptions-item label="登记人">{{
                detailData.registrant || '-'
              }}</a-descriptions-item>
              <a-descriptions-item label="登记时间">{{
                detailData.registerTime || '-'
              }}</a-descriptions-item>
            </a-descriptions>
          </a-card>
        </div>
      </a-spin>
    </a-modal>
  </div>
</template>

<style scoped>
.page-container {
  background: rgba(255, 255, 255, 0.7);
  backdrop-filter: blur(20px) saturate(180%);
  border-radius: 16px;
  padding: 32px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.04);
}

.page-header {
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.06);
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #1d1d1f;
  margin: 0 0 8px 0;
  letter-spacing: -0.5px;
}

.page-desc {
  font-size: 14px;
  color: #86868b;
  margin: 0;
}

.page-content {
  margin-top: 24px;
}

.search-card {
  background: #fff;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.02);
}

.search-form {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.search-actions {
  display: flex;
  justify-content: flex-end;
}

.table-wrapper {
  background: #fff;
  border-radius: 12px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.02);
}

.detail-content {
  padding: 8px 0;
}

.detail-section {
  margin-bottom: 24px;
  background: #fafafa;
  border-radius: 8px;
}

.detail-section :deep(.ant-card-head) {
  background: transparent;
  border-bottom: 1px solid rgba(0, 0, 0, 0.06);
  padding: 16px 24px;
}

.detail-section :deep(.ant-card-head-title) {
  font-size: 16px;
  font-weight: 600;
  color: #1d1d1f;
}

.detail-section :deep(.ant-card-body) {
  padding: 24px;
}

.detail-section :deep(.ant-descriptions-item-label) {
  font-weight: 500;
  background: #f5f5f5;
}

.items-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.items-group {
  background: #fff;
  padding: 16px;
  border-radius: 8px;
  border: 1px solid rgba(0, 0, 0, 0.06);
}

.items-group-title {
  font-size: 14px;
  font-weight: 600;
  color: #1d1d1f;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 2px solid #1890ff;
  display: inline-block;
}

.items-group:last-child .items-group-title {
  border-bottom-color: #ff4d4f;
}
</style>
